<?php
$pluginName = "customize";
$plugCnName = "全能DIY";
$phpPath = "/php/check-update.php";
$respPath = "https://gitee.com/fs185085781/kod-plugins";
error_reporting(0);
function getPluginsPath(){
    $tmpUrl = $_SERVER['SCRIPT_FILENAME'];
    $tmpUrl = str_replace('\\','/',$tmpUrl);
    $pathSz = explode("/",$tmpUrl);
    $pathCount = count($pathSz);
    $tmpUrl = "";
    for($i=0;$i<$pathCount-3;$i++){
        $tmpUrl=$tmpUrl.$pathSz[$i]."/";
    }
    return $tmpUrl;
}
function getConfigLocalFileUrl(){
    return getPluginsPath().$GLOBALS['pluginName']."/package.json";
}
function getDownUrl($versionStr,$isBd){
    $bdName = "";
    if($isBd){
        $bdName = "Bd";
    }
    $index = strpos($versionStr, "download/".$GLOBALS['pluginName'].$bdName.".zip");
    $versionStr = substr($versionStr,0,$index);
    $index = strrpos($versionStr,'href="');
    return "https://gitee.com".substr($versionStr,$index+6)."download/".$GLOBALS['pluginName'].$bdName.".zip";
}
function getUpdateText($versionStr){
    $index = strpos($versionStr, "download/".$GLOBALS['pluginName'].".zip");
    $versionStr = substr($versionStr,0,$index);
    $index2 = strrpos($versionStr,'markdown-body');
    $versionStr = substr($versionStr,$index2,$index-$index2);
    $versionStr = str_replace(array("\r\n", "\r", "\n"), "", $versionStr);
    $index = strpos($versionStr, "</p>");
    return substr($versionStr,15,$index-11);
}
function unzip_file($file, $destination){
    $zip = new ZipArchive() ;
    if ($zip->open($file) !== TRUE) {
        return;
    }
    $flag = $zip->extractTo($destination);
    $zip->close();
    return $flag;
}
function findVersion($str){
    $sz = explode("\"",$str);
    $ri = 0;
    for($i=0;$i<count($sz);$i++){
        if($sz[$i] == "version"){
            $ri = $i;
            break;
        }
    }
    return $sz[$ri+2];
}
function updateDialog($version){
    return '(function(){$.dialog({title:"'.$GLOBALS['plugCnName'].'升级",content:"<iframe src=\'./plugins/'.$GLOBALS['pluginName'].$GLOBALS['phpPath'].'?type=2&version='.$version.'\'></iframe>",width:300,height:200})})()';
}
function noNeedUpdate($version){
    return '(function(){console.log("版本一致无需更新:'.$version.'");})()';
}
function return_data($flag,$msg,$data){
    $res = array("flag"=>$flag,"msg"=>$msg);
    if(!empty($data)){
        $res["data"] = $data;
    }
    $str = json_encode($res);
    return $str;
}
function is_https() {
    if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
        return true;
    } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    } elseif ( !empty($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], "https")===0) {
        return true;
    }
    return false;
}
function getCdn(){
    $str = file_get_contents("../cdn.js");
    $str = strstr($str,"http");
    $str = strstr($str,'"',true);
    return $str;
}
function getOptions(){
    $actionPhp = "http".(is_https()?"s":"")."://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
    $acUrlSz = explode("/",$actionPhp);
    $url = "";
    for($i=0;$i<count($acUrlSz)-4;$i++){
        $url = $url.$acUrlSz[$i]."/";
    }
    $url = $url."?user/view/options";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, false);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_COOKIE, "CSRF_TOKEN=".$_COOKIE['CSRF_TOKEN']."; KOD_SESSION_ID=".$_COOKIE['KOD_SESSION_ID']."; ");
    $res = curl_exec($curl);
    curl_error($curl);
    curl_close($curl);
    $res = json_decode($res,true);
    return $res;
}
if($_GET['type'] == "1"){
    //加载js,用于判断是否需要更新
    $options = getOptions();
    if(!$options || !$options['data'] || !$options['data']['user'] || !$options['data']['user']['isRoot'] || $options['data']['user']['isRoot'] != 1){
        //提示
        echo noNeedUpdate("非管理员,不提示");
        return;
    }
    $remote = file_get_contents($respPath."/raw/master/".$pluginName."/package.json");
    $local = file_get_contents(getConfigLocalFileUrl());
    $localVersion = findVersion($local);
    $remoteVersion = findVersion($remote);
    if($localVersion == $remoteVersion){
        echo noNeedUpdate($remoteVersion);
        return;
    }
    echo updateDialog($remoteVersion);
}else if($_GET['type'] == "2"){
    //更新界面
    $version = $_GET['version'];
    $versionStr=file_get_contents($respPath."/releases");
    $text = getUpdateText($versionStr);
    $downUrl = getDownUrl($versionStr,false);
    $actionPhp = "http".(is_https()?"s":"")."://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
    $cdn = getCdn()."/updateDialog";
    $html = file_get_contents($cdn."/index.html");
    $html = str_replace('src="asserts','src="'.$cdn.'/asserts',$html);
    $html = '<script>window.version="'.$version.'";window.text="'.$text.'";window.downUrl="'.$downUrl.'";window.actionPhp="'.$actionPhp.'";</script>'.$html;
    echo $html;
}else if($_GET['type'] == "3"){
    //自定更新接口
    $version = $_GET['version'];
    $local = file_get_contents(getConfigLocalFileUrl());
    $localVersion = findVersion($local);
    if($version == $localVersion){
        echo return_data(false,"当前与线上版本一致,无需更新",null);
        return;
    }
    $fileName = $version.".zip";
    if(!file_exists($fileName)){
        $versionStr=file_get_contents($respPath."/releases");
        $flag = file_put_contents($fileName,file_get_contents(getDownUrl($versionStr,$_GET['ac']==3)));
        if(!$flag){
            echo return_data(false,"下载失败",null);
            return;
        }
    }
    if(!unzip_file($fileName,getPluginsPath())){
        echo return_data(false,"文件解压失败",null);
        return;
    }
    if(!unlink($fileName)){
        echo return_data(false,"删除失败",null);
        return;
    }
    $local = file_get_contents(getConfigLocalFileUrl());
    $localVersion = findVersion($local);
    if($version != $localVersion){
        echo return_data(false,"自动升级失败,请尝试手动升级",null);
        return;
    }
    echo return_data(true,"自动升级成功",null);
}